#ifndef __M_OBJECT_H__
#define __M_OBJECT_H__
#include "Common.hpp"

template<class T>
class ObjectPool
{
public:
    T* New()
    {
        T* obj = nullptr;
        //优先把还回来的内存块对象，再次重复利用
        if (_freeList)
        {
            void* next = *((void**)_freeList);
            obj = (T*)_freeList;
            _freeList = next;
        }
        else
        {
            if (_remainBytes < sizeof(T))
            {
                _remainBytes = 128 * 1024;
                _memory = (char*)SystemAlloc(_remainBytes);
                if (_memory == nullptr)
                {
                    throw std::bad_alloc();
                }
            }
            
            obj = (T*)_memory;
            size_t objSize = sizeof(T) < sizeof(void*) ? sizeof(void*) : sizeof(T);
            _memory += objSize;
            _remainBytes -= objSize;
        }

        new(obj)T;//定位new,在obj处显示调用T的构造函数初始化
        return obj;
    }

    void Delete(T* obj)
    {
        //显示调用T的析构函数清理对象
        obj->~T();

        *(void**)obj = _freeList;
        _freeList = obj;
    }
private:
    char* _memory = nullptr; //指向大块内存
    size_t _remainBytes = 0; //大块内存的剩余字节数
    void* _freeList = nullptr; //归还回来的小块内存的自由链表
};

#endif